#include "tcp.h"
#include <iostream>

using namespace std;

void TCPState::changeState(TCPConnection* con, TCPState* state)
{
	con->changeState(state);
}

//////////////////////////////////////////////////////
TCPState* TCPOpenedState::m_state = NULL;

TCPState* TCPOpenedState::instance()
{
	if (NULL == m_state)
	{
		m_state = new TCPOpenedState();

		static TCPOpenedStateCleaner cleaner;
	}
	
	return m_state;
}

void TCPOpenedState::open(TCPConnection* p_conn)
{
	cout<<"TCP is already opened."<<endl;
}

void TCPOpenedState::close(TCPConnection* p_conn)
{
	cout<<"TCP is closed now."<<endl;
	changeState(p_conn, TCPClosedState::instance());
}

void TCPOpenedState::work(TCPConnection* p_conn)
{
	cout<<"TCP is working... ok"<<endl;
}

//////////////////////////////////////////////////////
TCPState* TCPClosedState::m_state = NULL;

TCPState* TCPClosedState::instance()
{
	if (NULL == m_state)
	{
		m_state = new TCPClosedState();

		static TCPClosedStateCleaner cleaner;
	}

	return m_state;
}

void TCPClosedState::open(TCPConnection* p_conn)
{
	cout<<"TCP is opened now."<<endl;
	changeState(p_conn, TCPOpenedState::instance());
}

void TCPClosedState::close(TCPConnection* p_conn)
{
	cout<<"TCP is already closed."<<endl;
}

void TCPClosedState::work(TCPConnection* p_conn)
{
	cout<<"TCP is closed and couldn't work! :("<<endl;
}

//////////////////////////////////////////////////////

TCPConnection::TCPConnection()
{
	m_TCPState = TCPClosedState::instance();
}

void TCPConnection::open()
{
	m_TCPState->open(this);
}

void TCPConnection::close()
{
	m_TCPState->close(this);
}

void TCPConnection::work()
{
	m_TCPState->work(this);
}

void TCPConnection::changeState(TCPState* state)
{
	m_TCPState = state;
}
